package com.yatoooon.screenadaptation.utils;

import ohos.agp.components.Component;

import java.lang.reflect.Method;

/**
 * ViewUtils;
 *
 * @since 2021-04-13
 */
public class ViewUtils {
    private static final String METHOD_GET_MAX_WIDTH = "getMaxWidth";
    private static final String METHOD_GET_MAX_HEIGHT = "getMaxHeight";
    private static final String METHOD_GET_MIN_WIDTH = "getMinWidth";
    private static final String METHOD_GET_MIN_HEIGHT = "getMinHeight";
    private static final String METHOD_SET_MAX_WIDTH = "setMaxWidth";
    private static final String METHOD_SET_MAX_HEIGHT = "setMaxHeight";

    /**
     * setMaxWidth
     *
     * @param view
     * @param value
     */
    public static void setMaxWidth(Component view, int value) {
        setValue(view, METHOD_SET_MAX_WIDTH, value);
    }

    /**
     * setMaxHeight
     *
     * @param view
     * @param value
     */
    public static void setMaxHeight(Component view, int value) {
        setValue(view, METHOD_SET_MAX_HEIGHT, value);
    }

    /**
     * setMinWidth
     *
     * @param view
     * @param value
     */
    public static void setMinWidth(Component view, int value) {
        view.setMinWidth(value);
    }

    /**
     * setMinHeight
     *
     * @param view
     * @param value
     */
    public static void setMinHeight(Component view, int value) {
        view.setMinHeight(value);
    }

    /**
     * getMaxWidth
     *
     * @param view
     * @return int
     */
    public static int getMaxWidth(Component view) {
        return getValue(view, METHOD_GET_MAX_WIDTH);
    }

    /**
     * getMaxHeight
     *
     * @param view
     * @return int
     */
    public static int getMaxHeight(Component view) {
        return getValue(view, METHOD_GET_MAX_HEIGHT);
    }

    /**
     * getMinWidth
     *
     * @param view
     * @return int
     */
    public static int getMinWidth(Component view) {
        return view.getMinWidth();
    }

    /**
     * getMinHeight
     *
     * @param view
     * @return int
     */
    public static int getMinHeight(Component view) {
        return view.getMinHeight();
    }

    private static int getValue(Component view, String getterMethodName) {
        int result = 0;
        try {
            Method getValueMethod = view.getClass().getMethod(getterMethodName);
            result = (int) getValueMethod.invoke(view);
        } catch (Exception e) {
            // do nothing
        }
        return result;
    }

    private static void setValue(Component view, String setterMethodName, int value) {
        try {
            Method setValueMethod = view.getClass().getMethod(setterMethodName);
            setValueMethod.invoke(view, value);
        } catch (Exception e) {
            // do nothing
        }
    }
}
